/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Button, Form, InputNumber, notification, Select, Table} from 'antd';

import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import {FormField, FormLayout, ModalFooter} from "antd-extra";
import notify from "../../../components/NotificationExtra";
import ViewTitle from "../../../components/ViewTitle";
import styles from "../../index.less";
import _ from "lodash";
import MaterialElement from "../../finance/modal/MaterialElement";

const {Option} = Select;
moment.locale('zh-cn');
const table = 'ProcureOrder';
@Form.create()
@connect(({
            user,
            global,
            store,
            material,
            procure
          }) => ({...user, ...material, ...store, ...global, ...procure}))
export default class ModalSelectStoreLots extends FormBase {
  constructor(props) {
    super(props);
    const {record = {}} = this.props;
    this.state = {...record, selectedRowKeys: []};
  }

  componentDidMount() {
    const {record = {}} = this.props;
    const {code} = record;
    this.props.dispatch({
      type: 'store/findInboundLots',
      payload: {code}
    });
  }

  renderFoot = () => {
    const {foot, value, modalRef, form, inboundLots, callback} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            const {modalRef, record = {}} = this.props;
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              const {selectedRowKeys = []} = this.state;
              if (selectedRowKeys.length === 0) {
                notify({type: 'error', message: '请选择入库批次'});
                return;
              }

              const key = selectedRowKeys[0];
              const prod = _.find(inboundLots, item => {
                return item.lotCode === key;
              });
              const {materialContent, materialCount} = values;
              prod.materialContent = materialContent;
              prod.materialCount = materialCount;
              callback(prod);
              modalRef.close();
            });
          }}>确定</Button>

          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };

  onSearch = searchText => {
    const {materials = []} = this.props;
    if (!searchText || searchText === '') {
      this.state.materials = materials;
      const _temp = this.state;
      this.setState(_temp);
      return;
    }
    const temp = [];
    _.map(this.props.materials, item => {
      const {name} = item;
      if (name.includes(searchText)) {
        temp.push(item);
      }
    });
    const _temp = this.state;
    _temp.materials = temp;
    this.setState(_temp);
  };

  materialTableCol() {
    return [
      {
        title: '原料编码', key: 'code', dataIndex: "code", render: (value, record) => {
          const {code, name} = record;
          return <MaterialElement code={code} name={name}></MaterialElement>;
        }
      },

      {title: '原料类型', key: 'type', dataIndex: "type"},
      {title: '原料编号', key: 'number', dataIndex: "number"},
      {title: '原料形态', key: 'subcategory', dataIndex: "subcategory"},
      {title: '供应商', key: 'vendor', dataIndex: "vendor"},
      {title: '去向', key: 'target', dataIndex: "target"},
      {title: '去向客户', key: 'customer', dataIndex: "customer"},
      {
        title: '可用数量', key: 'inboundCount', dataIndex: "inboundCount", render: (value, record) => {
          const {usedCount = 0} = record;
          return <div color={'#229'}>{value - usedCount}</div>;
        }
      },
      {title: '入库数量', key: 'inboundCount', dataIndex: "inboundCount"},
      {title: '入库时间', key: 'inboundDate', dataIndex: "inboundDate"}

    ];
  }

  onSelectChange = selectedRowKeys => {
    this.setState({selectedRowKeys});
  };

  render() {
    const {style, inboundLots = [], form, count = 0, isPkg = false} = this.props;
    console.log('inboundLots', inboundLots);
    const {selectedRowKeys, materialContent, materialCount} = this.state;
    const _materialCount = count * materialContent / 100;
    const rowSelection = {
      type: 'radio',
      selectedRowKeys,
      onChange: this.onSelectChange
      // getCheckboxProps: record => ({
      //   disabled: _.find(selectedProds, item => {
      //     return item.pmLotId === record.pmLotId;
      //   })
      // })
    };
    const onSelectRow = (record) => {
      const {lotCode} = record;
      const temp = _.find(selectedRowKeys, item => {
        return item === lotCode;
      });
      if (temp) {
        _.remove(selectedRowKeys, item => item === lotCode);
      } else {
        selectedRowKeys.length = 0;
        selectedRowKeys.push(record.lotCode);
      }
      this.onSelectChange(selectedRowKeys, record);
    };
    return (
      <div style={{...style}}>
        {isPkg ? <FormLayout form={form} cols={2}>
          <FormField
            label={'原料用量'} required={true}
            name={'materialCount'} initialValue={materialCount}
          >
            <InputNumber style={{width: '100%'}}></InputNumber>
          </FormField>
        </FormLayout> : <FormLayout form={form} cols={2}>
          <FormField
            label={'原料含量%'}
            name={'materialContent'} initialValue={materialContent}
          >
            <InputNumber onChange={(value) => {
              this.state.materialContent = value;
              this.componentDidMount();
            }} style={{width: '100%'}}></InputNumber>
          </FormField>
          <FormField
            label={'原料用量'}
            name={'materialCount'} initialValue={_materialCount}>
            <InputNumber disabled style={{width: '100%'}}></InputNumber>
          </FormField>
        </FormLayout>}
        {<ViewTitle
          title={'入库批次记录'}
        ></ViewTitle>}
        {<Table
          className={styles.antTable}
          bordered={true}
          rowSelection={rowSelection}
          rowKey={record => record.lotCode}
          onRow={(record) => ({
            onClick: () => onSelectRow(record)
          })}
          columns={this.materialTableCol()}
          dataSource={inboundLots}
          scroll={{x: true}}
          pagination={true}
        ></Table>}
        {this.renderFoot()}
      </div>

    );
  }
}

